import utils from "./utils"

 function generalRequest (config) {
  return new Promise((resolve, reject) => {
    let data = config.method === 'get' ? config.params : config.data
    var header = {
      'content-type': 'application/json; charset=utf-8',
      'cookie': wx.getStorageSync('sessionid')
    }
    // 检查有没有拼在URL里面的参数
    Object.keys(data).map(key => {
      var keyStr = '{' + key + '}'
      var index = config.url.indexOf(keyStr)
      if (index !== -1) {
        config.url = config.url.replace(keyStr, data[key])
        delete data[key]
      }
    })
    // wx小程序 发起请求相应 log 就可以看到熟悉的返回啦
    wx.request({
      url: config.url,
      method: config.method,
      header,
      data,
      success: (res) => {
        var cookie = res.header['Set-Cookie']
        if (cookie != null) {
          let cookies = utils.cookiefy(cookie).cookies
          cookies.CLSYSSESSIONID && wx.setStorageSync('sessionid', `CLSYSSESSIONID=${cookies['CLSYSSESSIONID']}`)
        }
        if (res.statusCode === 200) {
          return resolve(res)
        } else if (res.statusCode === 401) {
          wx.showModal({
            title: '系统提示',
            content: '账号登录过期，请重新登录',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
              if(result.confirm){
                wx.reLaunch({
                  url: '/pages/login/login'
                })
              }
            },
            fail: ()=>{},
            complete: ()=>{}
          })
        } else if (res.statusCode === 500) {
          return reject(new Error('网络异常，请刷新后再试'))
        } else {
          return reject(new Error('网络错误'))
        }
      },
      fail: (err) => {
        return reject(err)
      }
    })
  })
}

function get (url, params) {
  return generalRequest({
    method: 'get',
    url: url,
    params: params
  })
}

function post (url, params) {
  return generalRequest({
    method: 'post',
    url: url,
    data: params
  })
}

function put (url, params) {
  return generalRequest({
    method: 'put',
    url: url,
    data: params
  })
}

export default {
  get,
  post,
  put
}
